import React, { useState, useEffect, useImperativeHandle } from 'react';
import { Button, Icon, message, Progress } from 'antd';
import COMMONATION from 'service/apis/commonAction';
import { connect } from 'dva';
import pic from 'dic/pic';
import './index.styl';

/*
 * 图片 文档 pdf上传组件
 */
function UploadPanelIE({
  cRef,
  dispatch,
  commonAction: { uploadInfo },
  getFileList,
  editFileList,
  isNone,
  actionType,
  num,
  mb,
  uploadNum,
  flag,
  id,
  tip,
  index = 0,
  getFileName
}) {
  const [fileLists, setFileList] = useState([]);
  const [fileName, setFileName] = useState([]);
  const [picObj] = useState(pic.obj);
  const [uploadError, setUploadError] = useState(false);
  useImperativeHandle(cRef, () => ({
    fileLists,
    fileName
  }));
  useEffect(() => {
    dispatch({
      type: 'commonAction/getToken',
    });
  }, [dispatch]);

  useEffect(() => {
    if (actionType === 'edit') {
      // setFileName([])
      setFileList(editFileList)
    }
  }, [actionType, editFileList])
  useEffect(() => {
    if (id !== undefined) {
      // setFileName([])
      setFileList([])
    }
  }, [id])
  useEffect(() => {
    if (uploadError) {
      message.error('上传失败', 2, () => {
        setUploadError(false)
      });
    }
  }, [uploadError])

  function openFile() {
    const InputFile = document.getElementById('_file')
    InputFile.click()
  }

  function submitFile(e) {
    let _number = 0;
    const img_type = ['jpg', 'jpeg', 'png', 'doc', 'docx', 'pdf']
    const ori_file_name = e.target.value.split("\\")[e.target.value.split("\\").length - 1]
    if (fileLists.length >= Number(num)) {
      message.error(`文件个数不超过${num}个`);
      return
    }
    if (!(img_type.includes(ori_file_name.split('.')[ori_file_name.split('.').length - 1].toLowerCase()))) {
      message.error(`文件格式不正确，请重新上传`);
      return
    }
    const form = document.forms[index]
    form.submit()
    const targetIframe = document.getElementById('_targetIframe')
    targetIframe.addEventListener('load', function () {
      const preArray = document.getElementById('_targetIframe').contentDocument.getElementsByTagName('pre');
      const data = preArray[0].innerText
      const code = data.split('code=')[1].split(',')[0]
      if (code === '000000') {
        if (_number === 0) {
          _number++;
          message.success(`上传成功`);
        }
        const dataObj = JSON.parse(data.split('data=')[1].split(')')[0])
        setFileList([...fileLists, {
          fileName: dataObj.url.split('/')[dataObj.url.split('/').length - 1],
          fileType: pic.typeCode[dataObj.url.split('/')[dataObj.url.split('/').length - 1].split('.')[dataObj.url.split('/')[dataObj.url.split('/').length - 1].split('.').length - 1]],
          fileUrl: dataObj.url
        }])
        getFileList([...fileLists, {
          fileName: dataObj.url.split('/')[dataObj.url.split('/').length - 1],
          fileType: pic.typeCode[dataObj.url.split('/')[dataObj.url.split('/').length - 1].split('.')[dataObj.url.split('/')[dataObj.url.split('/').length - 1].split('.').length - 1]],
          fileUrl: dataObj.url
        }])
      } else {
        message.error(`上传失败`);
      }
    })

  }

  // 删除文件
  const deleteFile = value => {
    const { fileName } = value;
    fileLists.map((item, index) => {
      if (item.fileName === fileName) {
        fileLists.splice(index, 1);
      }
    });
    getFileList(fileLists);
    setFileList([...fileLists]); // 防止潜复制
  }
  return (
    <div className="UploadPanel" style={{ display: isNone ? 'block' : 'none' }}>
      <div className="flexWrapper" style={{ display: isNone ? 'block' : 'none' }}>
        <div>
          <Button className="btn fix-btn" onClick={openFile}>
            <Icon type="upload"/> 上传
          </Button>
          <form
            action={COMMONATION.UPLOAD_IMG_IE9}
            method="post"
            enctype="multipart/form-data"
            hidden="hidden"
            target="_targetIframe"
          >
            <input type="file" onChange={submitFile} name="file" id="_file"/>
            <input type="hidden" name="Authorization" value={'Bearer ' + uploadInfo.token}/>
          </form>
          <iframe name="_targetIframe" id="_targetIframe" style={{display: 'none'}}></iframe>
        </div>
        <div>
          <div>{`1.请上传${tip}，支持格式：doc、docx、pdf、jpg、jpeg、png。`}</div>
          <div>2.最多可上传{num}个文件，单个文件不大于{mb}M</div>
        </div>
      </div>

      <div className="fileWrapper">
        <div className='itembox'>
          {/* {
            fileName.length > 0 && fileName.map(item => {
              if (item.percent === 100 && item.show) {
                return null
              }
              return (
                <div className="uploading" key={randomString(16)}>
                  <div>
                    <img src={upload} alt="" />
                  </div>
                  <div className="upload-pro">
                    {item.name}
                    <Progress percent={item.percent || 0} showInfo={false} />
                  </div>
                </div>
              )
            })
          } */}
          {fileLists.length > 0 &&
            fileLists.map((item, index) => {
              return (
                <div className="item" key={'x' + index}>
                  <div className='imgs'>
                    <img
                      src={
                        picObj[item.fileType] ||
                        picObj[item.fileUrl.split('.')[item.fileUrl.split('.').length - 1]]
                      }
                      alt={''}
                    />
                  </div>
                  <div className="name">{item.name || item.fileName}</div>
                  <div className="icon">
                    <Icon type="close" onClick={() => deleteFile(item)} style={{ fontSize: '0.14rem' }} />
                  </div>
                </div>
              );
            })}
        </div>
      </div>
    </div>
  );
}

export default connect(({ commonAction }) => ({
  commonAction,
}))(UploadPanelIE);
